package com.egg.ylt.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.egg.ylt.R;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.CustomUtils;
import com.egg.ylt.Utils.DateUtils;
import com.egg.ylt.Utils.StatusBarUtil;
import com.egg.ylt.datePicker.CustomDatePicker;
import com.egg.ylt.presenter.impl.AddGrowRecordPresenterImpl;
import com.egg.ylt.view.IAddGrowRecordView;
import com.yonyou.framework.library.base.BaseActivity;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.utils.AppDateUtil;
import com.yonyou.framework.library.common.utils.MoneyFormatUtil;
import com.yonyou.framework.library.common.utils.ScreenUtil;
import com.yonyou.framework.library.common.utils.StringUtil;
import com.yonyou.framework.library.common.utils.ToastUtil;
import com.yonyou.framework.library.dialog.AlertDialog;
import com.yonyou.framework.library.widgets.datepicker.TimePickerDialog;
import com.yonyou.framework.library.widgets.datepicker.data.Type;
import com.yonyou.framework.library.widgets.datepicker.listener.OnDateSetListener;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by lijiateng on 2019/1/19.
 */

public class ACT_AddGrowRecord extends BaseActivity<AddGrowRecordPresenterImpl> implements IAddGrowRecordView, OnDateSetListener {

    public static final String KEY_BABY_WEIGHT = "key_baby_weight";
    public static final String KEY_BABY_HEIGHT = "key_baby_height";
    public static final String KEY_BABY_DATE = "key_baby_date";
    public static final String KEY_BABY_ID = "key_baby_id";
    public static final String KEY_BABY_ITEM_ID = "key_baby_item_id";

    @BindView(R.id.rl_include_title)
    RelativeLayout mIncludeRlView;
    @BindView(R.id.ll_root)
    LinearLayout llRoot;
    @BindView(R.id.include_iv_back)
    ImageView ivBack;
    @BindView(R.id.include_tv_title)
    TextView tvTitle;
    @BindView(R.id.include_tv_right)
    TextView tvRight;
    @BindView(R.id.et_add_height)
    EditText etAddHeight;
    @BindView(R.id.et_add_weight)
    EditText etAddWeight;
    @BindView(R.id.tv_date)
    TextView tvDate;

    private CustomDatePicker customDatePicker;
    private TimePickerDialog timePickerDialog;
    private String babyHeight;
    private String babyWeight;
    private String babyDate;
    private String babyId;
    private String babyItemId;

    @Override
    public void showBusinessError(ErrorBean error) {
        switch (error.getCode()) {
            case "401":
                // 弹窗提示用户是否要覆盖之前的内容
                showCoverAlert(error.getMsg());
                break;
            default:
                showError(error.getMsg());
                break;
        }
    }

    @Override
    public void showError(String msg) {
        ToastUtil.makeText(mContext, msg, false);
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        babyHeight = extras.getString(KEY_BABY_HEIGHT, "");
        babyWeight = extras.getString(KEY_BABY_WEIGHT, "");
        babyDate = extras.getString(KEY_BABY_DATE, "");
        babyId = extras.getString(KEY_BABY_ID, "");
        babyItemId = extras.getString(KEY_BABY_ITEM_ID, "");
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_add_record;
    }

    @Override
    protected View getLoadingTargetView() {
        return llRoot;
    }

    @Override
    protected void initViewsAndEvents() {

        StatusBarUtil.setStatusBarColor(this, R.color.ylt_style_orange);
        StatusBarUtil.StatusBarLightMode(this);
        CustomUtils.setImmersiveStatusBar(mContext, mIncludeRlView);

        tvTitle.setText(!TextUtils.isEmpty(babyItemId) ? "编辑成长记录" : "新增成长记录");
        tvRight.setText("保存");
        ivBack.setVisibility(View.VISIBLE);
        tvRight.setVisibility(View.VISIBLE);

        MoneyFormatUtil.formatMoney(etAddHeight, null);
        MoneyFormatUtil.formatMoney(etAddWeight, null);

        // 如果是编辑，带入之前的信息
        etAddWeight.setText(StringUtil.getString(babyWeight));
        etAddHeight.setText(StringUtil.getString(babyHeight));
        String dateValue = TextUtils.isEmpty(babyDate) ?
                AppDateUtil.getTimeStamp(System.currentTimeMillis(), AppDateUtil.YYYY_MM_DD)
                : babyDate;
        tvDate.setText(dateValue);
//        initDatePicker(tvDate);

        timePickerDialog = initTimePickerDialog(System.currentTimeMillis());

        // 修改时不能修改时间
        if (!TextUtils.isEmpty(babyItemId)) {
            tvDate.setEnabled(false);
        }

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return true;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return TransitionMode.RIGHT;
    }

    @OnClick({R.id.include_iv_back, R.id.include_tv_right, R.id.tv_date})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.include_iv_back:
                if (mPresenter.verifyUserInput(true,
                        etAddHeight.getText().toString(), etAddWeight.getText().toString())) {
                    showQuitAlert();
                    return;
                }
                finish();
                break;
            case R.id.include_tv_right:

                // 如果是带入信息编辑，则弹窗提示
                if (!TextUtils.isEmpty(babyItemId)) {
                    showCoverAlert(babyItemId);
                    return;
                }

                // 保存新数据, itemId 为空
                requestModifyRecord("");
                break;
            case R.id.tv_date:
//                customDatePicker.show(tvDate.getText().toString());

                timePickerDialog.show(getSupportFragmentManager(), "year_month_day");

                break;
        }
    }

    /**
     * 新增或编辑宝宝记录
     *
     * @param itemId 当前条目的 itemId :
     *               <p>
     *               1. 如果是编辑则由上个页面传入；
     *               2. 新增该值为空；
     *               3. 新增的时候选择的日期已经对应了某条数据，则后端返回该条记录的 id，提示是否覆盖
     */
    private void requestModifyRecord(String itemId) {
        String height = etAddHeight.getText().toString();
        String weight = etAddWeight.getText().toString();
        String date = tvDate.getText().toString();
        mPresenter.addOrUpdateHeightAndWeight(height, weight, date, babyId, itemId);
    }

    /**
     * 编辑过数据后直接退出，提示数据会丢失
     */
    private void showQuitAlert() {
        final AlertDialog alertDialog = new AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_alert_quit)
                .setWidthAndHeight(ScreenUtil.dip2px(mContext, 300), ScreenUtil.dip2px(mContext, 180))
                .create();

        alertDialog.setOnClickListener(R.id.tv_cancel, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });

        alertDialog.setOnClickListener(R.id.tv_confirm, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                finish();
            }
        });

        alertDialog.show();
    }

    /**
     * 如果是带入信息编辑，则弹窗提示会覆盖
     *
     * @param itemId
     */
    private void showCoverAlert(final String itemId) {
        final AlertDialog alertDialog = new AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_alert_cover)
                .setWidthAndHeight(ScreenUtil.dip2px(mContext, 300), ScreenUtil.dip2px(mContext, 180))
                .create();

        alertDialog.setOnClickListener(R.id.tv_cancel, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });

        alertDialog.setOnClickListener(R.id.tv_confirm, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                requestModifyRecord(itemId);
            }
        });

        alertDialog.show();
    }

    @Override
    public void modifySucceed() {
        ToastUtil.makeText(mContext, "保存成功", false);
        readyGo(ACT_GrowUpRecord.class);
    }

    /**
     * 初始化时间选择器
     *
     * @param targetTv
     */
    public void initDatePicker(final TextView targetTv) {

        // 起始时间
        String startTime = "2012-01-01 00:00";
        if (Constants.BABYBIRTHDAY > 0) {
            startTime = AppDateUtil.getTimeStamp(Constants.BABYBIRTHDAY, AppDateUtil.YYYY_MM_DD_HH_MM);
        }
        String endTime = AppDateUtil.getTimeStamp(System.currentTimeMillis(), AppDateUtil.YYYY_MM_DD_HH_MM);

        // 时间滚轮
        customDatePicker = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                targetTv.setText(time.split(" ")[0]);
            }
        }, startTime, endTime); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker.showSpecificTime(true); // 显示时和分
        customDatePicker.setIsLoop(false); // 允许循环滚动
    }

    private TimePickerDialog initTimePickerDialog(long defalutTime) {

        long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;

        return new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setCancelStringId("取消")
                .setSureStringId("确定")
                .setTitleStringId("请选择时间")
                .setThemeColor(Color.parseColor("#FFB024"))
                .setWheelItemTextSize(14)
                .setMinMillseconds(Constants.BABYBIRTHDAY == 0 ? System.currentTimeMillis() - tenYears : Constants.BABYBIRTHDAY)
                .setMaxMillseconds(System.currentTimeMillis())
                .setCurrentMillseconds(defalutTime)
                .setCyclic(false)
                .setCallBack(this)
                .build();
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        tvDate.setText(AppDateUtil.getTimeStamp(millseconds, AppDateUtil.YYYY_MM_DD));
    }

}
